<template>
  <div class="insure">
    <x-header v-show="!isWeChar">
      <div slot="default" class="common__header--title">资料上传</div>
      <div @click="goBack" slot="overwrite-left"><img slot="icon" src="~assets/x3/ico/goback1.png" class="go-back"></div>
    </x-header>
    <group class="report__group">
      <div class="report__group_row" v-for="(item,index) in listNo" :key="index">
        <input :id="'file'+index" type="file" multiple size="20" accept="image/*" @change="onFileChange($event,index)" style="display: none;">
        <div class="row_label">
          <img v-if="index==0" src="~assets/x3/service/service_dljy.png">
          <img v-if="index==1" src="~assets/x3/service/service_sgdbc.png">
          <img v-if="index==2" src="~assets/x3/service/service_sgdbc.png">
          <img v-if="index==3" src="~assets/x3/ico/icon-card1.png">
          <img v-if="index==4" src="~assets/x3/ico/icon-occupation.png">
          <div v-if="titleList[index].sonTile.length===0">{{titleList[index].title}}</div>
          <div v-else>
            <span>{{titleList[index].title}}</span>
            <span class="sp">{{titleList[index].sonTile[0].title}}</span>
          </div>
        </div>
        <img class="addImages" @click="addPic(index)" src="~assets/x3/ico/x3_addImg.png">
        <div class="report__group_row_imgs" v-show="initData['showImages'+(index)].length >0">
          <div class="img" v-for="(image,i) in initData['showImages'+(index)]" :key="i" @click="delImg(index, i, image.name)">
            <img :src="image.data" :alt="i" />
          </div>
          <x-button @click.native="removeImageOfRow(index)">移除全部图片</x-button>
        </div>
        <div class="insure__footer">
          <div @click="reportImmediately()" class="report__rightbtn">{{textType}}</div>
        </div>
      </div>
    </group>
  </div>
</template>

<script>
import { RequestUrl } from "src/common/url";
import { Mutations, RouteUrl } from "src/common/const";
import { mapState, mapActions } from "vuex";
import { XHeader, Group, XInput, XButton } from "vux";
export default {
  components: { XHeader, Group, XInput, XButton },
  computed: mapState(
    { isLoading: "isLoading", isWeChar: "isWeChar", order: "order", seleValue: "seleValue" }),
  data() {
    return {
      textType: "资料上传",
      listNo: 5,//模块和子数组个数
      titleList: [
        { title: "事故环境", sonTile: [] },
        { title: "本车", sonTile: [] },
        { title: "三者车", sonTile: [{ title: "(可选)" }] },
        { title: "证件", sonTile: [{ title: "(可选)" }] },
        { title: "我的损失", sonTile: [{ title: "(可选)" }] }],
      initData: {
        showImages0: [],//界面显示的图片数组
        showImages1: [],//界面显示的图片数组
        showImages2: [],//界面显示的图片数组
        showImages3: [],//界面显示的图片数组
        showImages4: [],//界面显示的图片数组
        uploadAllImages: [],//上传的图片数组
      },
      upLoadType: 1,  //false 1资料上传 2 马上报案
      url: "",
    }
  },
  methods: {
    reportImmediately() {
      // if (this.$common.isEmpty(this.order.reportPolicyNo.policyNo)) {
      //   return this.showErrorMsg("保单号不能为空！");
      // }
      // if (this.$common.isEmpty(this.order.reportPolicyNo.email)) {
      //   return this.showErrorMsg("保单号不能为空！");
      // }
      let formData = new FormData();
      if (this.upLoadType == 1) {
        this.url = RequestUrl.REPORT_CLAIMS;
        formData.append("autoPolNo", this.seleValue.cliaimsData.autoPolNo);
        formData.append("incidentTime", this.seleValue.cliaimsData.incidentTime);
        formData.append("claimType", this.seleValue.cliaimsData.claimType);
        formData.append("province", this.seleValue.cliaimsData.province);
        formData.append("city", this.seleValue.cliaimsData.city);
        formData.append("incidentStreetAddress", this.seleValue.cliaimsData.incidentStreetAddress);
        formData.append("incidentNotes", this.seleValue.cliaimsData.incidentNotes);
        formData.append("userName", this.seleValue.cliaimsData.userName);
        formData.append("phoneNo", this.seleValue.cliaimsData.phoneNo);

      } else {
        this.url = RequestUrl.UPLOAD_PHOTO;
        formData.append("email", this.seleValue.cliaimsData.email);
        formData.append("reportNo", this.seleValue.cliaimsData.autoPolNo);
      }
      if (this.$common.isEmpty(this.initData.uploadAllImages) || this.initData.uploadAllImages.length < 1) {
        //提示信息
        this.$vux.alert.show({
          content: this.$common.alertMsg("请选择图片", "red;")
        });
        return;
      }
      for (let index = 0; index < this.initData.uploadAllImages.length; index++) {
        let element = this.initData.uploadAllImages[index];
        formData.append("imgFiles", element);
      }
      let _this = this;
      this.$common.storeCommit(this, Mutations.UPDATE_LOADING_STATUS, true);
      this.$http.post(this.url, formData).then(function (res) {
        _this.$common.storeCommit(_this, Mutations.UPDATE_LOADING_STATUS, false);
        if (res.status == false) {
          _this.showErrorMsg(res.resultMessage);
        } else {
          let msgData = {
            headerTitle: "信息提示",
            gaBackUrl: RouteUrl.INDEX,
            buttonUrl: RouteUrl.INDEX,
            title: "1",
            description: "1",
            buttonsType: "primary",
            buttonsText: "返回首页",
          }
          let data = {
            _this: _this,
            msgData: ""
          }
          if (_this.upLoadType == 1) {
            msgData.title = "报案成功，报案号:" + res.resultMessage;
            msgData.description = "稍后会有工作人员联系，请保持电话通畅。";
            data.msgData = msgData;
            _this.$common.storeCommit(_this, Mutations.SET_MSG_DATA, data);
            // _this.$vux.alert.show({ content: _this.$common.alertMsg("报案成功，报案号:" + res.resultMessage, "green;") });
          } else {
            msgData.title = "上传资料成功";
            msgData.description = "资料信息已经发送至工作人员。";
            data.msgData = msgData;

            _this.$common.storeCommit(_this, Mutations.SET_MSG_DATA, data);

            // _this.$vux.alert.show({ content: _this.$common.alertMsg("上传资料成功", "green;") });
          }
          // _this.$common.goUrl(_this, RouteUrl.SERVICE);
        }
      });
    },
    //选择文件
    addPic(index) {
      //IOS系统需要调用2次才能触发到click
      if (localStorage["BOTYPE"] == "I") {
        $("#file" + index).trigger('click');
        $("#file" + index).trigger('click');
      } else {
        $("#file" + index).trigger('click');
      }
      return false;
    },
    onFileChange(event, index) {
      //创建图片阅读器并显示图片
      switch (index) {
        case 0: this.createImage(event, index, "imageFileOne"); break;
        case 1: this.createImage(event, index, "imageFileTwo"); break;
        case 2: this.createImage(event, index, "imageFileThree"); break;
        case 3: this.createImage(event, index, "imageFileFour"); break;
        case 4: this.createImage(event, index, "imageFileFive"); break;
        default: break;
      }
    },
    //创建图片
    createImage(obj, index, filePrdfix) {
      let files = obj.target.files || obj.dataTransfer.files;
      if (!files.length) return;
      if (this.isNotImgFile(files)) {
        this.$vux.alert.show({ content: this.$common.alertMsg("请选择图片文件！", "red;") });
        return;
      }
      if (typeof FileReader === 'undefined') {
        this.$vux.alert.show({ content: this.$common.alertMsg("您的浏览器不支持图片上传，请升级您的浏览器", "red;") });
        return false;
      }
      let leng = files.length;
      for (let i = 0; i < leng; i++) {
        //源文件
        let nowFile = files[i];
        //创建新名称的原文件
        let newFile = new File([nowFile], filePrdfix + "_" + new Date().getTime() + "-" + i + ".jpg", { type: "image/jpeg" });
        let newFileName = newFile.name;
        //输出到界面
        let _this = this;
        let reader = new FileReader();
        reader.readAsDataURL(nowFile);
        reader.onload = function (event) {
          //根据模块追加图片
          _this.initData['showImages' + index].push({ data: event.target.result, name: newFileName });
        };
        //存放到上传图片数组中
        this.initData.uploadAllImages.push(newFile);
      }
    },
    //移除当前模块单个文件
    delImg(index, i, fileName) {
      //index=外循环下标
      //i = 内循环下标
      for (let j = 0; j < this.initData.uploadAllImages.length; j++) {
        let file = this.initData.uploadAllImages[j];
        if (fileName == file.name) {
          //删除上传数组中指定名称的文件
          this.initData.uploadAllImages.splice(j, 1);
          break;
        }
      }
      //移除当前模块单个文件
      this.initData['showImages' + index].splice(i, 1);
    },
    //移除当前模块全部文件
    removeImageOfRow(index) {
      let upFiles = this.initData.uploadAllImages;
      let showFiles = this.initData['showImages' + index];
      for (let i = 0; i < upFiles.length; i++) {
        for (let j = 0; j < showFiles.length; j++) {
          if (showFiles[j].name == upFiles[i].name) {
            //删除上传数组中指定名称的文件
            this.initData.uploadAllImages.splice(i, 1);
          }
        }
      }
      //移除当前模块全部文件
      this.initData['showImages' + index] = [];
    },
    // 检查是否为非图像文件
    isNotImgFile(files) {
      for (let i = 0; i < files.length; i++) {
        let t = files[i].type;
        if (!/image\/\w+/.test(t)) {
          return true;
        }
      }
    },
    showErrorMsg(errorMsg) {
      this.$vux.alert.show({ content: this.$common.alertMsg(errorMsg, "red;") });
      setTimeout(() => {
        this.$vux.alert.hide();
      }, 3000);
      return false;
    },
    goBack() {
      this.$common.goBack(this);
    },
  },
  beforeRouteEnter(to, from, next) {
    sessionStorage["REPORTUPLOAD_FORM_URL"] = from.path;
    next();
  },
  beforeMount() {
    if (sessionStorage["REPORTUPLOAD_FORM_URL"] == "/") {
      this.$common.goUrl(this, RouteUrl.INDEX);
    }
  },
  mounted() {
    if (this.order.reportPolicyNo.type == 1) {
      this.textType = "马上报案";
      this.upLoadType = this.order.reportPolicyNo.type;
    } else {
      this.upLoadType = this.order.reportPolicyNo.type;
      this.textType = "资料上传";
    }
    document.title = "资料上传";

    this.$init.subPageInit(this);
  }
};
</script>

<style  lang="scss">
.report__group {
  width: 100%;
  .weui-cells {
    padding: 5px 0px 80px 0px;
  }
}

.report__group_row {
  border: 1px solid #e7e7e7;
  margin: 15px 15px;
  padding: 10px 0px;
  height: max-content;
  .row_label {
    width: 120px;
    height: 100%;
    float: left;
    div {
      width: 100%;
      height: 20px;
      font-size: 14px;
      text-align: center;
      span {
        width: 100%;
      }
      .sp {
        font-size: 10px;
        color: #aaa;
      }
    }
    img {
      display: block;
      clear: both;
      width: 50px;
      height: auto;
      margin: 0px auto;
    }
  }
  .addImages {
    clear: both;
    width: 50px;
    height: auto;
    margin-top: 12px;
  }
}

.report__group_row_imgs {
  border-top: 1px solid #e7e7e7;
  padding: 10px;
  margin-top: 10px;
  .img {
    display: block;
    float: left;
    width: 50px;
    height: 50px;
    margin: 5px;
    border: 1px solid #ccc;
    padding: 10px;
    background: #ffffff url(~assets/x3/ico/close.png) no-repeat right top;
    img {
      display: block;
      width: 100%;
      height: 100%;
      margin: auto;
    }
  }
  .btn {
    width: 100%;
    margin: 10px auto;
    clear: both;
  }
}

.insure__footer {
  position: fixed;
  left: 0px;
  bottom: 0px;
  z-index: 5;
  width: 100%;
  height: 47px;
  background-color: white;
  div {
    height: 100%;
    line-height: 47px;
    text-align: center;
    font-size: 20px;
  }
  box-shadow: 0px 0px 10px 1px #efefef;
}

.report__rightbtn {
  background: #C8161D;
  color: #fff;
}
</style>
